<template>
  <van-skeleton v-show="state.loading" :row="3" />

  <div v-show="!state.loading" class="history-month">
    <!-- 时间区域筛选 -->
    <div class="date-range">
      <div @click="adjustMonth(-1)">
        <SvgIcon
          svg-name="arrow-left"
          color="var(--sub-title-color)"
          class-name="arrow-svg-date"
        />
      </div>
      <div class="time">{{ state.currentMonth }}</div>
      <div @click="adjustMonth(1)">
        <SvgIcon
          svg-name="arrow"
          color="var(--sub-title-color)"
          class-name="arrow-svg-date"
        />
      </div>
    </div>
    <!-- 统计图 -->
    <BarEchart :dataX="state.barDataX" :dataY="state.barDataY" />

    <!-- 数据统计 -->
    <div class="title">数据统计</div>
    <DataStatistics
      type="月"
      :total="Number(state.totalDuation)"
      :average="Number(state.averageDuration)"
      :counts="state.counts"
    />

    <!-- 刷牙得分参考范围 -->
    <div class="title">刷牙得分参考范围</div>
    <ScoreLevel />
  </div>
</template>

<script setup>
import DataStatistics from './DataStatistics.vue'
import ScoreLevel from './ScoreLevel.vue'
import BarEchart from './BarEchart.vue'

import { reactive, onMounted, onBeforeUnmount, watch } from 'vue'
import { getCurrentMonth, getNMonth } from '@/utils/util'
import { deviceId } from '@/utils/enum'

import { useRoute } from 'vue-router'
const route = useRoute()

watch(
  () => route.query,
  (to, from) => {
    // 在这里处理路由变化的逻辑
    if (to.random) {
      state.currentMonth = getMonthStr(getCurrentMonth(new Date()))
      state._month = getCurrentMonth(new Date())
      getHistoryParam(state._month)

      getMouthDay(
        state._month.getMonth(),
        getFirstDay(state._month),
        getLastDay(state._month)
      )
      clearInterval(state.timer)
      intervalEvent(state._month, state.currentMonth)
    } else {
      clearInterval(state.timer)
    }
  },
  {
    deep: true
  }
)

const state = reactive({
  barDataX: [
    // '6/1',
    // '6/2',
    // '6/3',
    // '6/4',
    // '6/5',
    // '6/6',
    // '6/7',
    // '6/8',
    // '6/9',
    // '6/10',
    // '6/11',
    // '6/12',
    // '6/13',
    // '6/14',
    // '6/15',
    // '6/16',
    // '6/17',
    // '6/18',
    // '6/19',
    // '6/20',
    // '6/21',
    // '6/22',
    // '6/23',
    // '6/24',
    // '6/25',
    // '6/26',
    // '6/27',
    // '6/28'
  ],
  // barDataY: [
  //   10, 52, 98, 70, 60, 90, 88, 10, 52, 98, 70, 60, 90, 88, 10, 52, 98, 70, 60,
  //   90, 88, 10, 52, 98, 70, 60, 90, 88
  // ],
  barDataY: [],
  _month: undefined,
  currentMonth: '',
  loading: true,
  timer: undefined
})

const getFirstDay = date => {
  return new Date(date.getFullYear(), date.getMonth(), 1).getDate()
}
const getLastDay = date => {
  return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate()
}

const getMouthDay = (month, firstDay, lastDay) => {
  state.barDataX = []
  state.barDataY = []
  for (let i = firstDay; i <= lastDay; i++) {
    state.barDataY.push(0)
    state.barDataX.push(`${month + 1}/${i}`)
  }
}

const getMonthStr = date => {
  return `${date.getFullYear()}年${date.getMonth() + 1}月`
}

const currentMonthDays = _D => {
  const currentDate = new Date(_D)
  const year = currentDate.getFullYear()
  const month = currentDate.getMonth()
  const numberOfDays = new Date(year, month + 1, 0).getDate()
  return numberOfDays
}

// 获取刷牙的历史记录
const getHistoryParam = c_date => {
  const firstDay = new Date(
    c_date.getFullYear(),
    c_date.getMonth(),
    1
  ).getDate()
  const lastDay = new Date(
    c_date.getFullYear(),
    c_date.getMonth() + 1,
    0
  ).getDate()

  const start = new Date(
    c_date.getFullYear(),
    c_date.getMonth(),
    Number(firstDay)
  ).getTime()
  const end = new Date(
    c_date.getFullYear(),
    c_date.getMonth(),
    Number(lastDay)
  ).getTime()

  const _D = new Date(start)
  let allDates = []
  for (let i = 0; i < currentMonthDays(start); i++) {
    const date = new Date(_D) // 创建一个副本，用于计算每一天的日期
    date.setDate(date.getDate() + i) // 计算每一天的日期

    Hejia.getHistoryParam(
      {
        // deviceId,
        paramName: ['brushRecord'],
        startDate: date.getTime(),
        endDate: date.getTime() + 86400000
      },
      function (arr) {
        if (arr.length) {
          arr = arr.filter((item, index, self) => {
            const itemVal = item.params[0].value
            return (
              index ===
              self.findIndex(obj => {
                const arrVal = obj.params[0].value
                return itemVal === arrVal
              })
            )
          })

          // 筛选刷牙有效时间
          arr = arr.filter(item => {
            const { value } = item.params[0]
            const duration = parseInt(value.substring(10, 14), 16)
            if (duration >= 30) {
              return item
            }
          })

          const sumArr = arr.map(item => {
            const { value } = item.params[0]
            const time = parseInt(value.substring(0, 8), 16)
            const score = parseInt(value.substring(8, 10), 16)

            return score
          })

          const sum = sumArr.reduce(
            (accumulator, currentValue) => accumulator + currentValue,
            0
          )

          const average = Math.ceil(sum / sumArr.length)

          state.barDataY[i] = average
        } else {
          state.barDataY[i] = 0
        }
        state.loading = false
      },
      function (msg, obj) {
        console.log(obj.resultCode + obj.resultCodeMessage)
      }
    )
    allDates.push(date.getDate()) // 将计算得到的日期添加到数组中
  }

  // 月统计
  Hejia.getHistoryParam(
    {
      // deviceId,
      paramName: ['brushRecord'],
      startDate: start,
      endDate: end + 86400000
    },
    function (arr) {
      state.totalDuation = 0

      if (arr.length) {
        arr = arr.filter((item, index, self) => {
          const itemVal = item.params[0].value
          return (
            index ===
            self.findIndex(obj => {
              const arrVal = obj.params[0].value
              return itemVal === arrVal
            })
          )
        })

        // 筛选刷牙有效时间
        arr = arr.filter(item => {
          const { value } = item.params[0]
          const duration = parseInt(value.substring(10, 14), 16)
          if (duration >= 30) {
            return item
          }
        })

        const sum = arr.map(item => {
          const { value } = item.params[0]
          const time = parseInt(value.substring(0, 8), 16)
          const score = parseInt(value.substring(8, 10), 16)
          const duration = parseInt(value.substring(10, 14), 16)
          state.totalDuation += duration

          return score
        })
        state.totalDuation = (state.totalDuation / 60).toFixed(1)
        state.counts = arr.length
        state.averageDuration = (state.totalDuation / arr.length).toFixed(1)
      } else {
        state.totalDuation = 0
        state.averageDuration = 0
        state.counts = 0
      }
    },
    function (msg, obj) {
      console.log(obj.resultCode + obj.resultCodeMessage)
    }
  )
}

const intervalEvent = (month, c_month) => {
  clearInterval(state.timer)
  state.timer = setInterval(() => {
    state.currentMonth = c_month
    state._month = getCurrentMonth(new Date())

    getHistoryParam(month)
  }, 1000 * 5)
}

const adjustMonth = n => {
  state.currentMonth = getMonthStr(getNMonth(state._month, n))
  state._month = getNMonth(state._month, n)

  clearInterval(state.timer)

  getHistoryParam(state._month)
  getMouthDay(
    state._month.getMonth(),
    getFirstDay(state._month),
    getLastDay(state._month)
  )

  intervalEvent(state._month, state.currentMonth)
}

onMounted(() => {
  state.currentMonth = getMonthStr(getCurrentMonth(new Date()))
  state._month = getCurrentMonth(new Date())
  getHistoryParam(state._month)

  getMouthDay(
    state._month.getMonth(),
    getFirstDay(state._month),
    getLastDay(state._month)
  )
  clearInterval(state.timer)
  intervalEvent(state._month, state.currentMonth)
})

onBeforeUnmount(() => {
  clearInterval(state.timer)
})
</script>

<style lang="less">
.van-skeleton-paragraph,
.van-skeleton-title {
  background-color: #ccc !important;
}
.history-month {
  .date-range {
    display: flex;
    align-items: center;
    padding: 0 12px;

    .time {
      flex: 1;
      font-size: 28px;
      color: var(--title-color);
      font-weight: bold;
      text-align: center;
    }
  }

  & > .title {
    font-size: 24px;
    font-weight: 500;
    color: var(--title-color);
    margin-top: 30px;
    margin-bottom: 20px;
  }
}
</style>
